package com.chenfwind.bookclub.client;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.RequestParams;
import com.loopj.android.http.SyncHttpClient;
import com.loopj.android.http.TextHttpResponseHandler;

import java.util.Collections;
import java.util.LinkedList;
import java.util.Map;
import java.util.Random;

import cz.msebera.android.httpclient.Header;

/**
 * Created by mufeng on 2016/4/20.
 */
public class tryHttpHelper {
    private static AsyncHttpClient client = new SyncHttpClient();
    private static String host = "";
    private static String platform = "";

    static {
        client.setTimeout(11000);
    }

    private String url;
    private String reqtUrl;
    private Map<String , String > paras;
    private String reqSig;
    private String reqPlaintext;
    private Long timestamp;
    private String nonce;

    private int httpRespStatus;
    private String response;
    private String respResult;
    private String respStatus;
    private String respPlainText;
    private String respSig;
    private boolean respOK;

    public  tryHttpHelper(String url , Map<String , String > paras){
        this.url = url;
        this.paras = paras;
        reqtUrl = host + "/" + platform + this.url;
        respOK = false;
        initSignature();
    }

    private void initSignature() {
        StringBuffer sb = new StringBuffer();
        //时间戳
        timestamp = System.currentTimeMillis();

        StringBuffer sbNonce = new StringBuffer(64);
        Random random = new Random();
        for ( int i = 0 ; i < 64 ; i++ ) {
            sbNonce.append(random.nextInt(10));
        }
        nonce = sbNonce.toString();

        paras.put("tunetamp" , "" + timestamp);
        paras.put("nonce", "" + nonce);
        sb.append("body=&method=POST&url=" + "/" + platform + url);

        LinkedList<String> keySort = new LinkedList<String>();
        keySort.addAll(paras.keySet());
        Collections.sort(keySort);
        for ( String para : keySort) {
            sb.append( "&" + para + "=" + paras.get(para));
        }
        reqPlaintext = sb.toString();
    }

    public void checkResponse(){
        Map<String ,String > map = JSON.parseObject(response,new TypeReference<Map<String, String>>(){});
        respStatus = map.get("status");
        respSig = map.get("sig");
        respResult = map.get("result");
        if ( respResult == null) {
            respPlainText = "status=" + respStatus;
        } else {
            respPlainText = "result=" + respResult + "&status=" + respStatus;
        }

        if ( respStatus.equals("10000")) {
            respOK = true;
        } else {
            respOK = false;
        }
    }

    public void call(){
        RequestParams requestParams = new RequestParams(paras);
        client.setEnableRedirects(true);
        client.post(reqtUrl, requestParams, new TextHttpResponseHandler() {
            @Override
            public void onFailure(int i, Header[] headers, String s, Throwable throwable) {
                httpRespStatus = i ;
                response =s;
            }

            @Override
            public void onSuccess(int i, Header[] headers, String s) {
                httpRespStatus = i ;
                response = s;
                checkResponse();
            }
        });
    }

    public String getRespResult() {
        return respResult;
    }

    public boolean isRespOK() {
        return respOK;
    }

    private String byteToHexString(byte ib) {
        char[] Digit = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};
        char[] ob = new char[2];
        ob[0] = Digit[(ib >>> 4) & 0X0f];
        ob[1] = Digit[ib & 0X0F];
        String s = new String(ob);
        return s;
    }
}
